package com.cn.wanxi.springtask.util;

import java.io.*;

/**
 * @ClassName FileUtil
 * @Description TODO
 * @Author JiJiang
 * @Date 2022/9/29 15:41
 * @Version 1.0
 */

public class FileUtil {


    public static int readFile(String orgFileAbsPath, String saveFileAbsPath, int readLength) {

        File orgFile = new File(orgFileAbsPath);
        if (!orgFile.exists()) {
            return 0;
        }
        File shadowFile = new File(saveFileAbsPath);
        //副本文件不存在
        if (!shadowFile.exists()) {
            //父级文件对象不存在（即没创建目录）
            if (!shadowFile.getParentFile().exists()) {
                //创建层级目录
                shadowFile.getParentFile().mkdirs();
            }
            try {
                //创建文件
                shadowFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
                return 0;
            }
        }


        try {
            FileInputStream fileInputStream = new FileInputStream(orgFile);
            FileOutputStream fileOutputStream = new FileOutputStream(shadowFile);
            //读取的总字节数
            int totalSize = 0;
            //每次的读取长度
            int readSize = 0;


            //region  使用缓冲读取
            //1M的缓冲区
//            byte[] buffer = new byte[1024];
//
//
//            while ((readSize = fileInputStream.read(buffer)) != -1) {
//
//                fileOutputStream.write(buffer, 0, readSize);
//                totalSize += readSize;
//            }
            //endregion


            byte[] buffer = new byte[1];

            while ((readSize = fileInputStream.read(buffer)) != -1) {

                totalSize += readSize;
                if (totalSize > readLength) {
                    break;
                }
                fileOutputStream.write(buffer, 0, readSize);


            }

            fileInputStream.close();
            fileOutputStream.close();
            return totalSize;

        } catch (FileNotFoundException e) {
            e.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();
        }
        return 0;


    }


}
